from django.http import JsonResponse
from django.views import View
from rest_framework_jwt.settings import api_settings

from role.models import SysRole
from user.models import SysUser
from user.models import SysUserSerializer

# Create your views here.
class TestView(View):
    def get(self, request):
        return JsonResponse({"code":200})
        # token =request.headers.get("AUTHORIZATION")
        # if token!=None and toke   n!='':
        #     print(token)
        #     SysUserList = SysUser.objects.values()
        #     print(SysUserList)
        #     return JsonResponse({"code": 200, "message": "查询成功！", "data": list(SysUserList)})
        # else:
        #     return JsonResponse({"code":200,"message":"认证失败"})

# token
class JwtTestView(View):
    def get(self, request):
        username = request.GET.get("username")
        password = request.GET.get("password")
        print(f"账号：{username},密码：{password}")
        user = SysUser.objects.get(username=username, password=password)
        if  user!=None:
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return JsonResponse({"code": 200, "token": token})
        else:
            return JsonResponse({"code":200,"message":"账号密码错误"})


class LoginView(View):
    def post(self,request):
        username=request.GET.get("username")
        password = request.GET.get("password")
        print(f"username={username},password={password}")
        try:
            user = SysUser.objects.get(username=username,password=password)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            roleList = SysRole.objects.raw(
                "SELECT id,`name` FROM sys_role WHERE id IN(SELECT role_id FROM sys_user_role WHERE user_id=" + str(
                    user.id)+")")
            print(roleList)
            for row in roleList:
                ""
            return JsonResponse({"code": 200, "info": "登录成功", "token": token, "user": SysUserSerializer(user).data})
        except Exception as e:
            print(e)
            return JsonResponse({"code":500,"info":"账号或密码错误"})